import path = require("path");
import { ServerConfig } from "../../config/ServerConfig";
import DateUtil from "../../engine/utils/DateUtil";
import { Logger } from "../../engine/utils/Logger";
import RandomUtil from "../../engine/utils/RandomUtil";
const fs = require('fs');

export class GameImgHelper {

    public static base64_to_imgurl(userid: number, upload_pic_type: number, imgData: string) {
        let base64 = imgData.replace(/^data:image\/\w+;base64,/, "");//去掉图片base64码前面部分data:image/png;base64
        if (base64.length > 0 && base64 != 'null') {
            let dataBuffer: Buffer = Buffer.from(base64, 'base64'); //把base64码转成buffer对象，
            return this.buffer_to_imgurl(userid, upload_pic_type, dataBuffer)
        }
    }

    public static buffer_to_imgurl(userid: number, upload_pic_type: number, dataBuffer: Buffer): string {
        let baseUploadPath = path.resolve() + "/public/upload/";
        if (!fs.existsSync(baseUploadPath)) {
            fs.mkdirSync(baseUploadPath);
        }
        // let fileName: string = userid + "-" + upload_pic_type+"-"+DateUtil.formatDateStr4(DateUtil.now()) + ".jpg"
        let fileName: string = userid + "-" + upload_pic_type + "-" + RandomUtil.nextInt(1, 999) + ".jpg"
        let filePath: string = baseUploadPath + "/" + fileName;
        fs.writeFile(filePath, dataBuffer, function (err) {//用fs写入文件
            if (err) {
                Logger.error(err);
            }
        });
        let serverConfig: ServerConfig = ServerConfig.randomWebServer()
        let imgurl: string = serverConfig.getHttpUrl() + "/upload/" + fileName;
        Logger.log("upload========imgurl====", imgurl);
        return imgurl;
    }
}